import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { MemberVo } from 'src/app/model/member-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';

@Component({
  selector: 'app-personal-passport',
  templateUrl: './personal-passport.component.html',
  styles: [``]
})
export class PersonalPassportComponent implements OnInit {
  public curMember: MemberVo | null;
  public errorMessage: string = '';
  public passport: any = {
    oldpswd: '',
    newpswd: '',
    confirmpswd: '',
    token: '',
    ip: '127.0.0.1'
  };
  //npm i ng-validate-equal --save @see://github.com/BaherWael/ng-validate-equal
  constructor(
    private title: Title,
    private router: Router,
    private memberStorage: MemberStorageService,
    private memberService: MemberService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.curMember = this.memberStorage.get();
    this.btnNaviSharedService.active(false);//不需要全局的导航
    this.passport.token = this.util.randomAlphaNumeric(8) || '123456';
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.passport.ip=ipAddr);
  }

  ngOnInit(): void {
    this.title.setTitle('个人中心:修改密码');
  }

  public updatePassport(submitBtn: HTMLButtonElement): void {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '正在提交数据...');
    //
    this.memberService.editPassword(this.curMember?.id ?? 0, this.passport.oldpswd, this.passport.newpswd, this.passport.token, this.passport.ip).subscribe({
      next: response => {
        //跳转:/member/home/passport/success
        this.router.navigate(['member', 'home', 'passport', 'success']);
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            this.errorMessage = (err.status === 417) ? '登录密码更新失败' : err.error;
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
        //
        submitBtn.disabled = false;
        submitBtn.setAttribute('value', '下一步');
      },
      complete: () => {
        console.log('[PersonalPassport-CTL]Completed');
      }
    });
  }
}
